<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <!-- 内容区放表单 -->
    <img :src="url" alt="" v-if="url" style="width: 350px; height: 350px; object-fil: cover" />
    <img src="@/assets/images/avatar.jpg" alt="" v-else />
    <div class="mybtn">
      <el-button type="primary" icon="el-icon-plus" @click="clickFile">选择图片</el-button>
      <input type="file" ref="file" style="display: none" @change="fileChange" />
      <el-button icon="el-icon-upload" type="success" :disabled="!url" @click="upload"
        >上传头像</el-button
      >
    </div>
  </el-card>
</template>

<script>
import { uploadAPI } from '@/api/user'
export default {
  data() {
    return {
      url: ''
    }
  },
  methods: {
    clickFile() {
      // 点击选择图片，触发文件域的单击事件
      this.$refs.file.click()
    },
    fileChange(e) {
      if (e.target.files.length <= 0) return
      const fileObj = e.target.files[0]
      const fr = new FileReader()
      fr.readAsDataURL(fileObj)
      // 普通函数的this指向window，我想要this指向上层函数，就必须使用箭头函数
      fr.onload = () => {
        this.url = fr.result // 把得到的base64格式，赋值给数据项中的url
      }
    },
    async upload() {
      const { data: res } = await uploadAPI(this.url)
      if (res.code === 0) {
        this.$message.success(res.message)
        // 调用vuex中的getUser方法，重新获取用户信息
        this.$store.dispatch('user/getUser')
        this.url = ''
      } else {
        this.$message.error(res.message)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.mybtn {
  margin-top: 10px;
}
</style>
